import UIKit

// 主视图控制者
class ViewController: UIViewController, GameCallback, InputBoxCallback {
    private var mGame: Game!                                // 游戏
    @IBOutlet private weak var mLabelInformation: UILabel!  // "关卡数"标签

    /**
     * 方向按钮的单击响应方法。
     * @param sender    用户单击的按钮
     */
    @IBAction private func onButtonDirectionClicked(_ sender: UIButton) {
        mGame.onFling(sender.tag)
    }

    /**
     * "重玩本关"按钮的单击响应方法。
     */
    @IBAction private func onButtonRestartClicked() {
        mGame.restart()
    }
    
    /**
     * "送关"按钮的单击响应方法。
     */
    @IBAction private func onButtonSelectLevelClicked() {
        // 创建输入对话框
        let tipText = String(format: NSLocalizedString("IDS_PLEASE_INPUT_NUMBER", tableName: "Main", comment: ""), Const.LEVEL_COUNT)
        let inputBox = InputBox(self, displayValue: mGame.level, maxValue: Const.LEVEL_COUNT, minValue: 1, tipText: tipText, viewController: self)
        
        // 显示输入对话框
        inputBox.show()
    }

    /**
     * "回退"按钮的单击响应方法。
     */
    @IBAction private func onButtonUndoClicked() {
        mGame.undo()
    }

    /**
     * 游戏结束事件的响应方法。
     * @param allOver   全部通关则为 true，否则为 false
     */
    internal func onGameOver(_ allOver: Bool) {
        var text: String
        if allOver {
            text = NSLocalizedString("IDS_WON_ALL_OVER", tableName: "Main", comment: "")
        } else {
            text = NSLocalizedString("IDS_WON", tableName: "Main", comment: "")
        }
        let messageBox = UIAlertController(title: nil, message: text, preferredStyle: .alert)
        let ok = NSLocalizedString("IDS_OK", tableName: "Main", comment: "")
        let action = UIAlertAction(title: ok, style: .default, handler: {
            (alerts: UIAlertAction) -> Void in
            if !allOver {
                self.mGame.gotoNextLevel()
            }
        })
        messageBox.addAction(action)
        super.present(messageBox, animated: true)
    }
    
    /**
     * 进入关卡事件的响应方法。
     * @param level 关卡数
     */
    internal func onGotoLevel(_ level: Int) {
        let text = NSLocalizedString("IDS_INFORMATION", tableName: "Main", comment: "")
        mLabelInformation.text = String(format: text, level, 0)
    }

    internal func onInputBoxCancel() {
    }

    /**
     * 输入窗口的"确定"按钮的单击响应方法。
     * @param intValue  用户输入的数值
     */
    internal func onInputBoxOK(_ intValue: Int) {
        mGame.gotoLevel(intValue)
    }
    
    internal func onInputBoxOK(_ stringValue: String) {
    }

    /**
     * 小人移动件的响应方法。
     * @param moveCount 移动次数
     */
    internal func onManMoved(_ moveCount: Int) {
        let text = NSLocalizedString("IDS_INFORMATION", tableName: "Main", comment: "")
        mLabelInformation.text = String(format: text, mGame.level, moveCount)
    }

    /**
     * 隐藏状态栏。
     */
    internal override var prefersStatusBarHidden: Bool {
        return true
    }

    /**
     * 视图加载事件的响应方法。
     */
    internal override func viewDidLoad() {
        super.viewDidLoad()

        // 获取所有控件
        let buttonUp = view.viewWithTag(Const.TAG_BUTTON_UP)!
        let buttonDown = view.viewWithTag(Const.TAG_BUTTON_DOWN)!
        let buttonLeft = view.viewWithTag(Const.TAG_BUTTON_LEFT)!
        let buttonRight = view.viewWithTag(Const.TAG_BUTTON_RIGHT)!
        let buttonRestart = view.viewWithTag(Const.TAG_BUTTON_RESTART) as! UIButton
        let buttonSelectLevel = view.viewWithTag(Const.TAG_BUTTON_SELECT_LEVEL) as! UIButton
        let buttonUndo = view.viewWithTag(Const.TAG_BUTTON_UNDO) as! UIButton

        // 禁用 translatesAutoresizingMaskIntoConstraints，否则控件约束将无效
        buttonUp.translatesAutoresizingMaskIntoConstraints = false
        buttonDown.translatesAutoresizingMaskIntoConstraints = false
        buttonLeft.translatesAutoresizingMaskIntoConstraints = false
        buttonRight.translatesAutoresizingMaskIntoConstraints = false
        buttonRestart.translatesAutoresizingMaskIntoConstraints = false
        buttonSelectLevel.translatesAutoresizingMaskIntoConstraints = false
        buttonUndo.translatesAutoresizingMaskIntoConstraints = false
        mLabelInformation.translatesAutoresizingMaskIntoConstraints = false

        // 获取可用的最大屏幕尺寸
        let screenWidth = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        
        // 计算格的尺寸
        BaseGameObject.sSize = Int(screenWidth) / Const.GAME_BOARD_GRID_COUNT_H

        // 设置背景色
        view.backgroundColor = Const.COLOR

        // 设置标签的文字
        let text = NSLocalizedString("IDS_INFORMATION", tableName: "Main", comment: "")
        mLabelInformation.text = String(format: text, 1, 0)

       // 创建游戏区域
        let gameBoardWidth = CGFloat(BaseGameObject.sSize * Const.GAME_BOARD_GRID_COUNT_H)
        let gameBoardHeight = CGFloat(BaseGameObject.sSize * Const.GAME_BOARD_GRID_COUNT_V)
        let gameBoardX = (screenWidth - gameBoardWidth) / 2.0
        let gameBoardY = gameBoardX
        let gameBoard = GameBoard(frame: CGRect(x: gameBoardX, y: gameBoardY, width: gameBoardWidth, height: gameBoardHeight))
        view.addSubview(gameBoard)

        // 计算控件比例
        var scale_button_width = Const.SCALE_BUTTON_WIDTH_IPHONE
        var scale_button_height = Const.SCALE_BUTTON_HEIGHT_IPHONE
        var scale_direction_size = Const.SCALE_DIRECTION_SIZE_IPHONE
        var scale_font_size = Const.SCALE_FONT_SIZE_IPHONE
        var scale_padding = Const.SCALE_PADDING_IPHONE
        if screenHeight - gameBoardHeight - scale_direction_size * CGFloat(BaseGameObject.sSize) * 2 - scale_padding * CGFloat(BaseGameObject.sSize) * 3 < 0.0 {
            scale_button_width = Const.SCALE_BUTTON_WIDTH_IPAD
            scale_button_height = Const.SCALE_BUTTON_HEIGHT_IPAD
            scale_direction_size = Const.SCALE_DIRECTION_SIZE_IPAD
            scale_font_size = Const.SCALE_FONT_SIZE_IPAD
            scale_padding = Const.SCALE_PADDING_IPAD
        }
        
        // 设置文字尺寸
        let textSize = CGFloat(BaseGameObject.sSize) * scale_font_size
        let font = UIFont.systemFont(ofSize: textSize)
        buttonRestart.titleLabel?.font = font
        buttonSelectLevel.titleLabel?.font = font
        buttonUndo.titleLabel?.font = font
        mLabelInformation.font = font
        
        // 计算控件尺寸
        let button_width = CGFloat(BaseGameObject.sSize) * scale_button_width
        let button_height = CGFloat(BaseGameObject.sSize) * scale_button_height
        let direction_size = CGFloat(BaseGameObject.sSize) * scale_direction_size
        let control_padding = CGFloat(BaseGameObject.sSize) * scale_padding

        // 控件布局
        /* "关卡数"标签 */
        let lcLabelInformationRight = NSLayoutConstraint(item: mLabelInformation!, attribute: .right, relatedBy: .equal, toItem: buttonRight, attribute: .right, multiplier: 1.0, constant: 0)
        view.addConstraint(lcLabelInformationRight)
        
        let lcLabelInformationY = NSLayoutConstraint(item: mLabelInformation!, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcLabelInformationY)
        
        /* "右移"按钮 */
        let lcButtonRightWidth = NSLayoutConstraint(item: buttonRight, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonRight.addConstraint(lcButtonRightWidth)

        let lcButtonRightHeight = NSLayoutConstraint(item: buttonRight, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonRight.addConstraint(lcButtonRightHeight)

        let lcButtonRightX = NSLayoutConstraint(item: buttonRight, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonRightX)

        let lcButtonRightY = NSLayoutConstraint(item: buttonRight, attribute: .bottom, relatedBy: .equal, toItem: mLabelInformation, attribute: .top, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonRightY)

        /* "下移"按钮 */
        let lcButtonDownWidth = NSLayoutConstraint(item: buttonDown, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonDown.addConstraint(lcButtonDownWidth)

        let lcButtonDownHeight = NSLayoutConstraint(item: buttonDown, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonDown.addConstraint(lcButtonDownHeight)

        let lcButtonDownX = NSLayoutConstraint(item: buttonDown, attribute: .right, relatedBy: .equal, toItem: buttonRight, attribute: .left, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonDownX)

        let lcButtonDownY = NSLayoutConstraint(item: buttonDown, attribute: .bottom, relatedBy: .equal, toItem: buttonRight, attribute: .bottom, multiplier: 1.0, constant: 0)
        view.addConstraint(lcButtonDownY)

        /* "上移"按钮 */
        let lcButtonUpWidth = NSLayoutConstraint(item: buttonUp, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonUp.addConstraint(lcButtonUpWidth)

        let lcButtonUpHeight = NSLayoutConstraint(item: buttonUp, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonUp.addConstraint(lcButtonUpHeight)

        let lcButtonUpX = NSLayoutConstraint(item: buttonUp, attribute: .left, relatedBy: .equal, toItem: buttonDown, attribute: .left, multiplier: 1.0, constant: 0.0)
        view.addConstraint(lcButtonUpX)

        let lcButtonUpY = NSLayoutConstraint(item: buttonUp, attribute: .bottom, relatedBy: .equal, toItem: buttonDown, attribute: .top, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonUpY)

        /* "左移"按钮 */
        let lcButtonLeftWidth = NSLayoutConstraint(item: buttonLeft, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonLeft.addConstraint(lcButtonLeftWidth)

        let lcButtonLeftHeight = NSLayoutConstraint(item: buttonLeft, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: direction_size)
        buttonLeft.addConstraint(lcButtonLeftHeight)

        let lcButtonLeftX = NSLayoutConstraint(item: buttonLeft, attribute: .right, relatedBy: .equal, toItem: buttonDown, attribute: .left, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonLeftX)

        let lcButtonLeftY = NSLayoutConstraint(item: buttonLeft, attribute: .bottom, relatedBy: .equal, toItem: buttonDown, attribute: .bottom, multiplier: 1.0, constant: 0)
        view.addConstraint(lcButtonLeftY)
        
        /* "回退"按钮 */
        let lcButtonUndoWidth = NSLayoutConstraint(item: buttonUndo, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: button_width)
        buttonUndo.addConstraint(lcButtonUndoWidth)
        
        let lcButtonUndoHeight = NSLayoutConstraint(item: buttonUndo, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: button_height)
        buttonUndo.addConstraint(lcButtonUndoHeight)
        
        let lcButtonUndoX = NSLayoutConstraint(item: buttonUndo, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: control_padding)
        view.addConstraint(lcButtonUndoX)
        
        let lcButtonUndoY = NSLayoutConstraint(item: buttonUndo, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonUndoY)

        /* "选关"按钮 */
        let lcButtonSelectLevelWidth = NSLayoutConstraint(item: buttonSelectLevel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: button_width)
        buttonSelectLevel.addConstraint(lcButtonSelectLevelWidth)
        
        let lcButtonSelectLevelHeight = NSLayoutConstraint(item: buttonSelectLevel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: button_height)
        buttonSelectLevel.addConstraint(lcButtonSelectLevelHeight)
        
        let lcButtonSelectLevelX = NSLayoutConstraint(item: buttonSelectLevel, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: control_padding)
        view.addConstraint(lcButtonSelectLevelX)
        
        let lcButtonSelectLevelY = NSLayoutConstraint(item: buttonSelectLevel, attribute: .bottom, relatedBy: .equal, toItem: buttonUndo, attribute: .top, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonSelectLevelY)
        
        /* "重玩本关"按钮 */
        let lcButtonRestartWidth = NSLayoutConstraint(item: buttonRestart, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: button_width)
        buttonRestart.addConstraint(lcButtonRestartWidth)

        let lcButtonRestartHeight = NSLayoutConstraint(item: buttonRestart, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: button_height)
        buttonRestart.addConstraint(lcButtonRestartHeight)

        let lcButtonRestartX = NSLayoutConstraint(item: buttonRestart, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1.0, constant: control_padding)
        view.addConstraint(lcButtonRestartX)

        let lcButtonRestartY = NSLayoutConstraint(item: buttonRestart, attribute: .bottom, relatedBy: .equal, toItem: buttonSelectLevel, attribute: .top, multiplier: 1.0, constant: -control_padding)
        view.addConstraint(lcButtonRestartY)

        // 创建游戏
        mGame = Game(self, drawer: gameBoard.drawer, gameBoard: gameBoard)
    }
}
